package com.huika.renrench.ui;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnCameraChangeListener;
import com.amap.api.maps.AMap.OnInfoWindowClickListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.AMap.OnMarkerDragListener;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.huika.renrench.R;
import com.huika.renrench.control.common.base.BaseAct;
import com.huika.renrench.support.bean.LocationBean;
import com.huika.renrench.support.bean.LocationBean.MyLocationListener;
import com.huika.renrench.utils.GaodeMapHelper;
import com.huika.renrench.view.TitleBarHelper;
/**
 * 高德地图类,地图选点
 * @author fanxing 创建于 Mar 21, 2015
 */
public class GaodeMapActivity extends BaseAct implements LocationSource, MyLocationListener, DialogInterface.OnClickListener, OnMarkerDragListener, OnGeocodeSearchListener, OnInfoWindowClickListener, OnCameraChangeListener, OnMarkerClickListener, InfoWindowAdapter {
	public static final String LOCATION_BEAN = "locationbean";
	
	private AMap aMap;
	private MapView mapView;
	private OnLocationChangedListener mListener;
	private GaodeMapHelper gaodeMapHelper;
	private LocationBean locationBean;
	private boolean isLocated;

	private GeocodeSearch geocoderSearch;

//	private Marker myMarker;

	private TextView tv_select_address;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gaode_location);
		
		TitleBarHelper titleBar = new TitleBarHelper(this, R.string.common_confirm, R.string.map_select_point);
		titleBar.setOnRightClickListener(this);
		tv_select_address = (TextView)findViewById(R.id.tv_select_address);
		mapView = (MapView) findViewById(R.id.map);
		mapView.onCreate(savedInstanceState);// 此方法必须重写
		init();
		showToastMsg("定位中...");
	}
	
	/**
	 * 初始化
	 */
	private void init() {
		if (aMap == null) {
			aMap = mapView.getMap();

			aMap.setLocationSource(this);// 设置定位监听
			aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
			aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
			// 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
			aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);
			aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
			
			//拖拽相关
			aMap.setOnMarkerDragListener(this);// 设置marker可拖拽事件监听器
			aMap.setOnInfoWindowClickListener(this);
			aMap.setOnCameraChangeListener(this);// 对amap添加移动地图事件监听器
			aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
		}
	}
	
	/**
	 * 方法必须重写
	 */
	@Override
	protected void onResume() {
		super.onResume();
		mapView.onResume();
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
		deactivate();
	}
	
	/**
	 * 方法必须重写
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
		if (gaodeMapHelper == null) {
			gaodeMapHelper.stop();
		}
	}
	
	/**
	 * 激活定位
	 */
	@Override
	public void activate(OnLocationChangedListener listener) {
		mListener = listener;
		if (gaodeMapHelper == null) {
			gaodeMapHelper = new GaodeMapHelper(this);
			gaodeMapHelper.setmLocationListener(this);
		}
		gaodeMapHelper.setMapLocationListener(mListener);
		gaodeMapHelper.start();
	}

	/**
	 * 停止定位
	 */
	@Override
	public void deactivate() {
		mListener = null;
		gaodeMapHelper.stop();
	}

	/**
	 * 定位结果
	 * @param locationBean
	 * @author FAN 创建于Mar 18, 2015
	 */
	@Override
	public void onLocation(LocationBean locationBean) {
		this.locationBean = locationBean;
		showToastMsg("定位成功："+locationBean.toString());
		isLocated = !(locationBean==null || TextUtils.isEmpty(locationBean.province));
		setResult(RESULT_OK, new Intent().putExtra(LOCATION_BEAN, this.locationBean));
		
		LatLng myll = new LatLng(locationBean.latitude, locationBean.longtitude);
		//拖拽相关
//		if(myMarker != null){
//			myMarker.setVisible(false);
//			myMarker.hideInfoWindow();
//		}
//		MarkerOptions markerOptions = new MarkerOptions();
//		markerOptions.title("我的位置")
//			.position(myll)
//			.draggable(false).perspective(true).period(50)
//			.snippet(locationBean.toString());
//		myMarker = aMap.addMarker(markerOptions);
		
		CameraUpdate update = CameraUpdateFactory.newCameraPosition(new CameraPosition(myll, 14, 0, 30));
		aMap.animateCamera(update);
		
		tv_select_address.setVisibility(View.VISIBLE);
		tv_select_address.setText(locationBean.toString());
	}
	
	@Override
	public void onBackPressed() {
		if(!isLocated){
			AlertDialog.Builder builder = new Builder(this);
			builder.setMessage("定位失败了，确定放弃定位？")
				.setNegativeButton("确定", this)
				.setPositiveButton("取消", this);
			builder.setCancelable(false);
			AlertDialog alertDialog = builder.create();
			alertDialog.setCanceledOnTouchOutside(false);
			alertDialog.show();
			return;
		}
		super.onBackPressed();
	}
	
	@Override
	public void onClick(DialogInterface dialog, int which) {
		switch (which) {
			case DialogInterface.BUTTON_POSITIVE:
				dialog.cancel();
				break;
			case DialogInterface.BUTTON_NEGATIVE:
				finish();
				break;
		}
	}
	
	@Override
	public void onClick(View v) {
		super.onClick(v);
		if(locationBean==null || TextUtils.isEmpty(locationBean.province)){
			showToastMsg("定位失败");
			return;
		}
		setResult(RESULT_OK, new Intent().putExtra(LOCATION_BEAN, this.locationBean));
		finish();
	}

	/**拖拽相关***************************************************/
	@Override
	public void onMarkerDrag(Marker arg0) {}

	@Override
	public void onMarkerDragEnd(Marker marker) {
		double latitude = marker.getPosition().latitude;
		double longitude = marker.getPosition().longitude;
		LatLonPoint latLonPoint = new LatLonPoint(latitude, longitude);
		geosearch(latLonPoint);
	}
	
	/**
	 * 逆地理编码
	 * 
	 * @author FAN 创建于Mar 19, 2015
	 */
	private void geosearch(LatLonPoint latLonPoint){
		showToastMsg("查询中...");
		if(geocoderSearch == null){
			geocoderSearch = new GeocodeSearch(this); 
			geocoderSearch.setOnGeocodeSearchListener(this); 
		}
		// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系   
		RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,GeocodeSearch.AMAP); 
		geocoderSearch.getFromLocationAsyn(query);
	}
	
	@Override
	public void onRegeocodeSearched(RegeocodeResult result, int rCode) { 
		dismissLoadingDialog();
	    if(rCode == 0){ 
	        if(result != null&&result.getRegeocodeAddress() != null 
	                 &&result.getRegeocodeAddress().getFormatAddress()!=null){ 
	        	RegeocodeAddress regeocodeAddress = result.getRegeocodeAddress();
	        	LatLonPoint latLonPoint = result.getRegeocodeQuery().getPoint();
	        	this.locationBean = LocationBean.saveCurrentLocation(latLonPoint.getLatitude(), 
	        			latLonPoint.getLongitude(), 
	        			regeocodeAddress.getProvince(), 
	        			regeocodeAddress.getCity(), 
	        			regeocodeAddress.getDistrict(), 
						0);
	        	locationBean.focusAddress = regeocodeAddress.getFormatAddress().replace(locationBean.toShortAddress(), "");
	    		showToastMsg("查找成功："+locationBean.toString());
	    		
	    		tv_select_address.setVisibility(View.VISIBLE);
	    		tv_select_address.setText(locationBean.toString());
	        }else{ 
	        	showToastMsg("未找到");
	        } 
	    }else{ 
	        showToastMsg("网络异常");
	    } 
	}

	@Override
	public void onMarkerDragStart(Marker arg0) {}

	@Override
	public void onGeocodeSearched(GeocodeResult arg0, int arg1) {}

	@Override
	public void onInfoWindowClick(Marker marker) {
		if(marker.isInfoWindowShown()){
			marker.hideInfoWindow();
		}else{
			marker.showInfoWindow();
		}
	}

	@Override
	public void onCameraChange(CameraPosition cameraPosition) {}

	@Override
	public void onCameraChangeFinish(CameraPosition cameraPosition) {
		float stand = 0.001f / cameraPosition.zoom;
		if(locationBean!=null && Math.abs(locationBean.latitude-cameraPosition.target.latitude)<stand && Math.abs(locationBean.longtitude-cameraPosition.target.longitude)<stand){
			return;
		}
		LatLonPoint latLonPoint = new LatLonPoint(cameraPosition.target.latitude, cameraPosition.target.longitude);
		geosearch(latLonPoint);
	}

	@Override
	public boolean onMarkerClick(Marker marker) {
		return false;
	}
	
	@Override
	public View getInfoContents(Marker marker) {
		if (marker.getTitle().equals("我的位置")) {
			View infoContentView = getLayoutInflater().inflate(R.layout.map_item, null);
			((TextView) infoContentView.findViewById(R.id.map_tv_name)).setText(marker.getSnippet());
			return infoContentView;
		}
		else {
			return null;
		}
	}

	@Override
	public View getInfoWindow(Marker arg0) {
		return null;
	}

	@Override
	public void setRootView() {
		// TODO Auto-generated method stub
		
	}
}
